package com.zgs.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zgs.common.constant.ProductConstant;
import com.zgs.mall.product.dao.AttrAttrgroupRelationDao;
import com.zgs.mall.product.dao.AttrGroupDao;
import com.zgs.mall.product.dao.CategoryDao;
import com.zgs.mall.product.entity.AttrAttrgroupRelationEntity;
import com.zgs.mall.product.entity.AttrGroupEntity;
import com.zgs.mall.product.entity.CategoryEntity;
import com.zgs.mall.product.service.CategoryService;
import com.zgs.mall.product.vo.AttrGroupRelationVo;
import com.zgs.mall.product.vo.AttrRespVo;
import com.zgs.mall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zgs.common.utils.PageUtils;
import com.zgs.common.utils.Query;

import com.zgs.mall.product.dao.AttrDao;
import com.zgs.mall.product.entity.AttrEntity;
import com.zgs.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao  attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catId,String attrType) {
        QueryWrapper<AttrEntity>  wrapper= new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(attrType)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(catId!=0){
            wrapper.eq("catelog_id",catId);
        }
       String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils= new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVoList = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //分类名称
            Long catelogId = attrEntity.getCatelogId();
            if (catelogId != null) {
                CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
                String catName = categoryEntity.getName();
                attrRespVo.setCatelogName(catName);
            }
            if("base".equalsIgnoreCase(attrType)){
                //属性分组名称
                Long attrId = attrEntity.getAttrId();
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
                if (attrAttrgroupRelationEntity != null) {
                    Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    if(attrGroupEntity !=null){
                        String attrGroupName = attrGroupEntity.getAttrGroupName();
                        attrRespVo.setGroupName(attrGroupName);
                    }
                }
            }

            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        //销售属性 不和 属性分组表关联
        if(attr.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() !=null){
            //保存关联关系
            AttrAttrgroupRelationEntity  attrAttrgroupRelationEntity =new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrSort(1);
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId,respVo);
       if (respVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
           //设置分组信息
           AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
           if (attrAttrgroupRelationEntity != null) {
               Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
               respVo.setAttrGroupId(attrGroupId);
               AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
               if(attrGroupEntity !=null){
                   String attrGroupName = attrGroupEntity.getAttrGroupName();
                   respVo.setGroupName(attrGroupName);
               }
           }
       }

        //设置分类信息
        Long catelogId = respVo.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        respVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity !=null){
            respVo.setCatelogName(categoryEntity.getName());
        }
        return respVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
       if (attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
           //修改属性分组关联
           AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
           relationEntity.setAttrGroupId(attr.getAttrGroupId());
           Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
           if (count>0){
               if(StringUtils.isEmpty(attr.getAttrGroupId())){
                   attrAttrgroupRelationDao.delete(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
               }else{
                   attrAttrgroupRelationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
               }
           }else{
               relationEntity.setAttrId(attr.getAttrId());
               attrAttrgroupRelationDao.insert(relationEntity);
           }
       }
    }

    /**
     * 根据属性分组id 查询所有关联的 属性关联的数据
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelation(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = attrAttrgroupRelationEntities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if (attrAttrgroupRelationEntities ==null || attrAttrgroupRelationEntities.isEmpty()){
            return null;
        }
        List<AttrEntity> list = this.listByIds(attrIds);
        return list;
    }

    /**
     * 删除属性与分组的关联关系
     * @param attrGroupRelationVos
     */
    @Transactional
    @Override
    public void deleteRelationDelete(AttrGroupRelationVo[] attrGroupRelationVos) {
        List<AttrAttrgroupRelationEntity> relationEntitys = Arrays.asList(attrGroupRelationVos).stream().map((relation) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(relation, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(relationEntitys);
    }

    /**
     * 获取当前分组没有关联的所有规格参数 属性
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getAttrNoRelation(Long attrgroupId, Map<String, Object> params) {
        //当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
          //当前分类下的所有分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> attrIds =null;
        if(attrGroupEntities !=null && !attrGroupEntities.isEmpty()){
            //获取分组下的所有 属性分组id attrGroupId
            List<Long> attrGroupIds = attrGroupEntities.stream().map(group -> {
                
                return group.getAttrGroupId();
            }).collect(Collectors.toList());
            //查询属性分组关联的 所有属性id
            QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<AttrAttrgroupRelationEntity>();
            if (attrGroupIds !=null && !attrGroupIds.isEmpty()){
                wrapper.in("attr_group_id",attrGroupIds);
            }
            List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(wrapper);
             attrIds = attrAttrgroupRelationEntities.stream().map(attrAttrgroupRelationEntity -> {
                return attrAttrgroupRelationEntity.getAttrId();
            }).collect(Collectors.toList());
        }
        //当前分组只能关联别的分组没有引用的属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type",1);
        if (attrIds !=null && !attrIds.isEmpty()){
            wrapper.notIn("attr_id",attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and(w->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {

        List<Long> list = baseMapper.selectSearchAttrIds(attrIds);
        return list;
    }


}